const wechat = require('wechat');
// const config = require('../../resources/WechatConfig').config;
const config = require('../../resources/WechatConfig').development;
const logger = require('../utils/Logger');
const api = require('../utils/WechatUtil');
const jsapiTicketService = require('./JsapiTicketService');
const accessTokenDao = require('../daos/AccessTokenDao');

let accessToken = '';

/**
 * @title 从微信获取新的 access_token
 */
const requestAccessTokenFromWechat = async () => {

    try {
        let token = await api.getAccessToken();
        accessToken = token.accessToken;
        let reTime = token.expireTime-Date.now();
        logger.info(`AccessToken ${accessToken} `);
        jsapiTicketService.queryJsapiTicketFromWechat (accessToken);
        if (token.expireTime) {
            setTimeout(() => {
                requestAccessTokenFromWechat();
                jsapiTicketService.queryJsapiTicketFromWechat (accessToken);
            }, (reTime - (300 * 1000)));
        }
    } catch (e) {
        logger.error(`access_token 从微信请求 access_token 失败`,e);
    }
};

let queryAccessTokenFromDatabase = async () => {

    try {
        let token = await accessTokenDao.find();
        if (expired(token)) {
            requestAccessTokenFromWechat();
        } else {
            accessToken = token[0].accessToken;
            logger.info(`access_token ${accessToken}`);
            let timeRemaining = token[0].expiresTime - Date.now();
            jsapiTicketService.initJsapiTicket (accessToken);

            setTimeout(function () {
                requestAccessTokenFromWechat();
            }, timeRemaining - 30000);
        }
    } catch (e) {
        logger.error('access_token从数据库获取access_token失败', +e)
    }
};

let expired = accessTokenInfo => {
    if (accessTokenInfo.length === 0) {
        return true;
    }
    else {
        let timeRemaining = accessTokenInfo[0].expireTime - Date.now();
        logger.info(`access_token 距离失效还有：${timeRemaining}毫秒`);
        return (accessTokenInfo.expiresTime - Date.now()) < 30000;
    }
};

module.exports = {
    /**
     *  校验微信服务端信息合法性
     *  更改服务器配置信息时
     */
    signFromWechat: wechat(config, (req, res, next) => {
        let message = req.weixin;
        console.log(message);
        res.reply('SUCCESS');
        next();
    }),
    initAccessToken: () => {
        queryAccessTokenFromDatabase();
    },
    getAccessToken: () => {
        return () => accessToken;
    },
};